//
//  GZSwitchCameraButton.swift
//  GLUZ
//
//  Created by lemon on 2025/3/11.
//

import UIKit

public protocol GZSwitchCameraButtonDelegate: AnyObject {
    func onGZSwitchCameraButtonClick(_ isFrontFacing: Bool)
}

extension GZSwitchCameraButtonDelegate {
    func onGZSwitchCameraButtonClick(_ isFrontFacing: Bool) { }
}

public class GZSwitchCameraButton: UIButton {
    
    public weak var delegate: GZSwitchCameraButtonDelegate?

    public var iconFrontFacingCamera: UIImage? {
        didSet {
            self.setTitle("切换摄像头", for: .normal)
        }
    }
    
    public var iconBackFacingCamera: UIImage? {
        didSet {
            self.setTitle("切换摄像头", for: .normal)
        }
    }
    
    public var isFrontFacing: Bool = true {
        didSet {
            if isFrontFacing {
                self.isSelected = false
                ZegoUIKit.shared.useFrontFacingCamera(isFrontFacing: true)
            } else {
                self.isSelected = true
                ZegoUIKit.shared.useFrontFacingCamera(isFrontFacing: false)
            }
        }
    }
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        self.isFrontFacing = true
        self.layer.cornerRadius = UIkitLiveAdaptLandscapeWidth(18)
        self.layer.masksToBounds = true
        self.backgroundColor = UIColor.colorWithHexString("#000000").withAlphaComponent(0.3)
        self.titleLabel?.numberOfLines = 0
        self.titleLabel?.font = UIFont.systemFont(ofSize: 8, weight: .regular)
        self.titleLabel?.textAlignment = .center
        self.setTitle("切换摄像头", for: .normal)
        self.setTitle("切换摄像头", for: .selected)
        self.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
    }
    
    required public init?(coder: NSCoder) {
        super.init(coder: coder)
        self.isFrontFacing = true
        self.layer.cornerRadius = UIkitLiveAdaptLandscapeWidth(18)
        self.layer.masksToBounds = true
        self.backgroundColor = UIColor.colorWithHexString("#000000").withAlphaComponent(0.3)
        self.titleLabel?.numberOfLines = 0
        self.titleLabel?.font = UIFont.systemFont(ofSize: 8, weight: .regular)
        self.titleLabel?.textAlignment = .center
        self.setTitle("切换摄像头", for: .normal)
        self.setTitle("切换摄像头", for: .selected)
        self.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
    }
    
    @objc func buttonClick(sender: UIButton) {
        self.isFrontFacing = !self.isFrontFacing
        self.delegate?.onGZSwitchCameraButtonClick(self.isFrontFacing)
    }

}

